package com.qf.interceptor;

import com.qf.bean.User;
import com.qf.constant.SSMContant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenInterceptor implements HandlerInterceptor{

    //拦截器的前处理  请求到达前端控制器之前
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception {

        //权限校验

        //1.获得session对象
        HttpSession session = request.getSession();

        //2.从session域中获取用户信息
        User user = (User) session.getAttribute(SSMContant.USER);


        //3.判断用户是否登入
        if(user != null) {
            //--》登入   放行
            return true;
        }else {
            //--》未登入 重定向到登入页面 拦截
            response.sendRedirect(request.getContextPath()+"/user/login");
            return false;
        }
    }
    //渲染视图之前处理
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object o,
                           ModelAndView modelAndView) throws Exception {
            //给modelAndView添加或修改数据
        System.out.println("渲染视图之前。。。");
    }
    //响应数据之前处理
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object o, Exception e) throws Exception {

        //粗力度查看访问量
        //记录日志
        System.out.println("响应数据之前。。。");
    }
}
